package com.stx.openeyes.view.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stx.openeyes.R;
import com.stx.openeyes.SealConst;
import com.stx.openeyes.dto.Response;
import com.stx.openeyes.model.User;
import com.stx.openeyes.utils.ContextUtil;
import com.stx.openeyes.utils.HttpAdress;
import com.stx.openeyes.utils.NToast;
import com.stx.openeyes.widget.ClearWriteEditText;
import com.stx.openeyes.widget.LoadDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mImgBackground;
    private ClearWriteEditText mPhoneEdit, mNickEdit, mPasswordEdit,mCodeEdit;
    private Button mConfirm;
    private String mPhone, mNickName, mPassword,mCode;
    protected Context mContext;
    private Gson mGson;
    private ImageView mCodeView;
    private String realCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = this;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        initView();

    }

    private void initView() {
        mPhoneEdit = (ClearWriteEditText) findViewById(R.id.reg_phone);
        mNickEdit = (ClearWriteEditText) findViewById(R.id.reg_username);
        mPasswordEdit = (ClearWriteEditText) findViewById(R.id.reg_password);
        mCodeEdit = (ClearWriteEditText) findViewById(R.id.reg_password2);
        mConfirm = (Button) findViewById(R.id.reg_button);
        mCodeView = findViewById(R.id.Code);
        mConfirm.setOnClickListener(this);
        //验证码初始化
        mCodeView.setImageBitmap(Code.getInstance().createBitmap());
        realCode = Code.getInstance().getCode().toLowerCase();

        TextView goLogin = (TextView) findViewById(R.id.reg_login);
        goLogin.setOnClickListener(this);

        mImgBackground = (ImageView) findViewById(R.id.rg_img_backgroud);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.translate_anim);
                mImgBackground.startAnimation(animation);
            }
        }, 10);

        addEditTextListener();
    }

    private void addEditTextListener() {
        mPhoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPasswordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 5) {
                    mConfirm.setClickable(true);
                    mConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
                } else {
                    mConfirm.setClickable(false);
                    mConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_gray));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Code:    //改变随机验证码的生成
                mCodeView.setImageBitmap(Code.getInstance().createBitmap());
                realCode = Code.getInstance().getCode().toLowerCase();
                break;
            case R.id.reg_login:
                finish();
                //startActivity(new Intent(this, LoginActivity.class));
                break;
            case R.id.reg_button:
                mPhone = mPhoneEdit.getText().toString().trim();
                mNickName = mNickEdit.getText().toString().trim();
                mPassword = mPasswordEdit.getText().toString().trim();
                mCode = mCodeEdit.getText().toString().trim();



                if (TextUtils.isEmpty(mNickName)) {
                    NToast.shortToast(mContext, getString(R.string.name_is_null));
                    mNickEdit.setShakeAnimation();
                    return;
                }
                if (mNickName.contains(" ")) {
                    NToast.shortToast(mContext, getString(R.string.name_contain_spaces));
                    mNickEdit.setShakeAnimation();
                    return;
                }

                if (TextUtils.isEmpty(mPhone)) {
                    NToast.shortToast(mContext, getString(R.string.phone_number_is_null));
                    mPhoneEdit.setShakeAnimation();
                    return;
                }
                if (TextUtils.isEmpty(mPassword)) {
                    NToast.shortToast(mContext, getString(R.string.password_is_null));
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
                if (mPassword.contains(" ")) {
                    NToast.shortToast(mContext, getString(R.string.password_cannot_contain_spaces));
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
                if(!mCode.equals(realCode)){
                    NToast.shortToast(mContext, "验证码错误");
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
                LoadDialog.show(mContext);
                requestRegister(mPhone, mPassword, mNickName);
                break;
        }
    }

    private void requestRegister(String mobile, String password, String nickname) {
        OkHttpUtils.post()
                .url(HttpAdress.REGISTER)
                .addParams("mobile", mobile)
                .addParams("password", password)
                .addParams("nickname", nickname)
                .addHeader("deviceId", ContextUtil.getDevicedId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("===register error", e.getMessage());
                        NToast.shortToast(mContext, SealConst.NETWORK_ERROR);
                        LoadDialog.dismiss(mContext);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("===reg response json", response);
                        mGson = new Gson();
                        Response<User> loginResp = mGson.fromJson(response, new TypeToken<Response<User>>() {}.getType());
                        if (!loginResp.isSuccess()) {
                            NToast.shortToast(mContext, loginResp.getMessage());
                            LoadDialog.dismiss(mContext);
                            return;
                        }
                        User useInfo = loginResp.getData();
                        LoadDialog.dismiss(mContext);
                        SharedPreferences settings = getSharedPreferences(SealConst.USER_INFO, 0);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(SealConst.SEALTALK_LOGIN_ID, useInfo.getUuid());
                        editor.commit();
                        startActivity(new Intent(mContext, FunctionActivity.class));
                    }
                });
    }
}
